package com.azt.provider.impl;

import com.alibaba.fastjson.JSONObject;
import com.azt.api.pojo.LevelRule;
import com.azt.api.pojo.req.LevelRuleReq;
import com.azt.api.service.LevelRuleService;
import com.azt.enums.LevelRuleCode;
import com.azt.model.page.Pagination;
import com.azt.provider.mapper.LevelRuleMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 规则管理
 * Created by LiQZ on 2017/4/13.
 */
@Service
public class LevelRuleServiceImpl implements LevelRuleService {

    @Autowired
    private LevelRuleMapper levelRuleMapper;

    @Override
    public Pagination listPage(int pageNo, int pageSize, Map<String, Object> params) {
        Page<Object> startPage = PageHelper.startPage(pageNo, pageSize);
        List<LevelRule> list = levelRuleMapper.selectByCondition(params);
        Pagination p = new Pagination(startPage, list);
        p.setList(list);
        return p;
    }

    @Override
    public List<LevelRule> listByType(Integer type) {
        List<String> codes = LevelRuleCode.getCodes(type);
        if (CollectionUtils.isEmpty(codes)) {
            return Collections.emptyList();
        }
        return levelRuleMapper.selectByCodes(codes);
    }

    @Override
    public void save(LevelRuleReq ruleReq) {
        JSONObject jsonObj = new JSONObject();
        if (ruleReq.getMaxAmountADay() != null) {
            jsonObj.put("max_amount_a_day", ruleReq.getMaxAmountADay());
        }
        if (ruleReq.getMaxCount() != null) {
            jsonObj.put("max_count", ruleReq.getMaxCount());
        }
        ruleReq.setLimitRule(jsonObj.toJSONString());
        LevelRule rule = new LevelRule();
        BeanUtils.copyProperties(ruleReq, rule);
        rule.setRemoved(0);
        if (ruleReq.getId() != null) {
            levelRuleMapper.updateByPrimaryKey(rule);
        } else {
            levelRuleMapper.insert(rule);
        }

    }

    @Override
    public void delete(Integer id, Integer value) {
        levelRuleMapper.updateRemoved(id, value);
    }

    @Override
    public LevelRule get(Integer id) {
        return levelRuleMapper.selectByPrimaryKey(id);
    }
}
